<template>
  <!-- 商品列表 -->
  <div class="sort-list-container">
    <ul>
      <li v-for="good in goodList" :key="good.id">
        <GoodItem :good="good" />
      </li>
    </ul>
  </div>
  <!-- 无限加载组件 -->
  <InfiniteLoad
    :isFinished="isFinished"
    :isLoading="isLoading"
    @load="loadNextPage"
  ></InfiniteLoad>
</template>

<script>
import GoodItem from './good-item.vue'
import { getSubCategoryGoodsApi } from '@/api/category'
import { inject, ref, watch } from 'vue'
import { useRoute } from 'vue-router'

export default {
  components: {
    GoodItem
  },
  setup () {
    const goodList = ref([])
    const route = useRoute()
    // 加载更多功能
    const isFinished = ref(false) // 是否加载完毕
    const isLoading = ref(false)
    const requestData = {
      page: 1,
      pageSize: 20,
      categoryId: route.params.id,
      sortField: null, // 排序类别
      attrs: [], // 商品属性
      brandId: null // 品牌名称
    }
    const filterParams = inject('filterParams')
    watch(() => filterParams.value, (newValue) => {
      console.log('筛选条件发生了变化', newValue)
      /**
       * 1. 合并参数（合并最新的过滤条件）
       * 2. 拿到最新参数发请求
       */
      goodList.value = []
      requestData.value = 0
      isFinished.value = false
      // const newParams = { ...requestData, ...newValue }
      // getSubCategoryGoods(newParams)
    }, {
      deep: true
    })
    // const getSubCategoryGoods = async (questParams) => {
    //   const { result } = await getSubCategoryGoodsApi(questParams)
    //   console.log('result', result)
    //   console.log('questData', questParams)
    //   goodList.value = result.items
    // }
    // getSubCategoryGoods(requestData)
    // 加载更多
    async function loadNextPage () {
      // 开启loading
      isLoading.value = true
      requestData.page++
      const { result } = await getSubCategoryGoodsApi({ ...requestData, ...filterParams.value })
      const newList = result.items
      // 追加列表数据
      goodList.value.push(...newList)
      // 关闭Loading
      isLoading.value = false
      if (result.counts === goodList.value.length) {
        // 列表加载完毕
        isFinished.value = true
      }
    }
    return { goodList, loadNextPage, isFinished, isLoading }
  }
}
</script>

<style lang="less" scoped>
.sort-list-container {
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
